#include "mystdio.h"
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>

MyFile* mfopen(const char* filename, const char* mode)
{
	//根据不同的方式来打开文件
	int fd = -1;
	if (strcmp(mode, "w") == 0)
	{
		fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC,UMASK);
	}
	else if (strcmp(mode, "a") == 0)
	{
		fd = open(filename, O_WRONLY | O_CREAT | O_APPEND, UMASK);
	}
	else if (strcmp(mode, "r") == 0)
	{
		fd = open(filename, O_RDONLY);
	}
	else{}

	if (fd < 0) perror("open");

	MyFile* fp = (MyFile*)malloc(sizeof(MyFile));
	if (!fp) return NULL;
	fp->fileno = fd;
	fp->flag = FLUSH_LINE;//默认是行刷新
	fp->curr = 0;
	fp->outbuffer[0] = 0;
	fp->cap = SIZE;
}

static void mfflush_core(MyFile* fp,int mode)
{
        if (fp->curr <= 0) return;//如果文件缓冲区没有数据就没必要接着刷新了
        if (mode == FORCE)
        {
                //强制刷新
                write(fp->fileno, fp->outbuffer, strlen(fp->outbuffer));
                fp->curr = 0;
        }
        else
        {
                //正常刷新
                if ((fp->flag & FLUSH_LINE) && fp->outbuffer[fp->curr - 1] == '\n')
                {
                        write(fp->fileno, fp->outbuffer, strlen(fp->outbuffer));
                        fp->curr = 0;
                }
                else if ((fp->flag & FLUSH_FULL) && fp->curr == fp->cap)
                {
                        write(fp->fileno, fp->outbuffer, strlen(fp->outbuffer));
                        fp->curr = 0;
                }
                else {};
        }
}


int mfwrite(const char* s, int size, MyFile* fp)
{
	//1.将用户定义的缓冲区中的内容刷新到文件缓冲区中
	memcpy(fp->outbuffer + fp->curr, s, strlen(s));//保证重复写入时能够接着往后写
	fp->curr += size;

	//2.将文件缓冲区的数据刷新到内核缓冲区中
	mfflush_core(fp, NORMAL);
	return size;
}

void mfflush(MyFile* fp)
{
	//强制刷新
	mfflush_core(fp, FORCE);
}

void mfclose(MyFile* fp)
{
	if (fp->fileno >= 0)
	{
		mfflush(fp);
		fsync(fp->fileno);
		close(fp->fileno);
		free(fp);
	}
}
